/* eslint react/no-string-refs:0 */
import React, { Component, Fragment } from 'react';
import { withRouter, Link } from 'react-router-dom';
import { Input, Button, Message, Select, Icon, Form, Table, Balloon } from '@alifd/next';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
// import Icon from '@icedesign/foundation-symbol';
import { DB_SETTING } from '../../utils/db';
import request from '../../utils/request';

const Option = Select.Option;
const FormItem = Form.Item;

@withRouter
class UserLogin extends Component {
  static displayName = 'UserLogin';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      hostList: [],
      editorHost: false,
      value: {
        username: '',
        password: '',
        host: '',
        checkbox: false,
      },
    };
  }
  componentDidMount() {
    this.getHostList();
  }
  formChange = (value) => {
    this.setState({
      value,
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.refs.form.validateAll((errors, values) => {
      if (errors) {
        console.log('errors', errors);
        return;
      }
      localStorage.setItem('serveHost', values.host);
      request.post('/user/login', {
        email: values.email,
        password: values.password,
      }).then((res) => {
        if (res.code === 200) {
          localStorage.setItem('authorization', res.data);
          Message.success('登录成功');
          this.props.history.push('/');
        } else {
          Message.error(res.message || '登录失败！');
        }
      });
    });
  };

  getHostList = () => {
    DB_SETTING().where('key').equals('host-list-setting').first()
      .then((response) => {
        if (response) {
          let res = response.value || '';
          res = JSON.parse(res);
          this.setState({
            hostList: res,
          });
        }
      })
      .catch((error) => {
        console.log('error', error);
      });
  }
  saveHostList = (hostList) => {
    DB_SETTING().where('key').equals('host-list-setting').first()
      .then((res) => { // 有记录
        if (res) {
          DB_SETTING().where('key').equals('host-list-setting')
            .modify({
              key: 'host-list-setting',
              value: JSON.stringify(hostList),
            })
            .then(() => {
              this.setState({
                editorHost: false,
              });
              Message.success('保存成功');
            });
        } else {
          DB_SETTING().add({
            key: 'host-list-setting',
            value: JSON.stringify(hostList),
          }).then(() => {
            this.setState({
              editorHost: false,
            });
            Message.success('保存成功');
          }).catch((e) => {
            Message.error(e.toString());
          });
        }
      })
      .catch(() => { // 没记录
        console.log('error');
      });
  }
  addHost = (item, valide) => {
    if (valide) {
      return false;
    }
    const { hostList } = this.state;
    const hostListNew = [...hostList, ...[item]];
    this.setState({
      hostList: hostListNew,
    });
    this.saveHostList(hostListNew);
  }
  showEditorHost = () => {
    this.setState({
      editorHost: true,
    });
  }
  removeHost = (record) => {
    console.log('record', record);
    const { hostList } = this.state;
    const hostListNew = hostList.filter((item) => {
      return item.hostLink !== record.hostLink;
    });
    this.setState({
      hostList: hostListNew,
    });
    this.saveHostList(hostListNew);
  }
  hideEditorHost = () => {
    this.setState({
      editorHost: false,
    });
  }
  renderDel = (value, index, record) => {
    const trigger = (<span style={{ color: 'red', textDecoration: 'underline' }}>删除</span>);
    return (
      <Balloon type="primary" trigger={trigger} closable={false} triggerType="click" align="t" >
        <Button warning size="small" onClick={this.removeHost.bind(this, record)}>确认删除</Button>
      </Balloon>
    );
  }
  render() {
    const { hostList, editorHost } = this.state;
    return (
      <div style={styles.container}>
        {
          !editorHost && (
            <Fragment>
              <h4 style={styles.title}>登 录</h4>
              <IceFormBinderWrapper
                value={this.state.value}
                onChange={this.formChange}
                ref="form"
              >
                <div style={styles.formItems}>
                  <div style={styles.formItem}>
                    <Icon type="account" size="small" style={styles.inputIcon} />
                    <IceFormBinder name="email" required message="必填">
                      <Input
                        maxLength={20}
                        placeholder="邮箱"
                        style={styles.inputCol}
                      />
                    </IceFormBinder>
                    <IceFormError name="username" />
                  </div>

                  <div style={styles.formItem}>
                    <Icon type="ellipsis" size="small" style={styles.inputIcon} />
                    <IceFormBinder name="password" required message="必填">
                      <Input
                        htmlType="password"
                        placeholder="密码"
                        style={styles.inputCol}
                      />
                    </IceFormBinder>
                    <IceFormError name="password" />
                  </div>
                  <div style={styles.formItem}>
                    <IceFormBinder name="host" required message="必填">
                      <Select style={styles.selector}>
                        {
                          hostList.map((item) => {
                            return item.hostLink && (<Option value={item.hostLink} key={item.hostLink}>{item.hostTitle}</Option>);
                          })
                        }
                      </Select>
                    </IceFormBinder>
                    <IceFormError name="password" />
                    <Icon type="set" size="small" onClick={this.showEditorHost} style={styles.setIcon} />
                  </div>

                  <div style={styles.footer}>
                    <Button
                      type="primary"
                      onClick={this.handleSubmit}
                      style={styles.submitBtn}
                    >
                      登 录
                    </Button>
                    <Link to="/user/register" style={styles.tips}>
                      立即注册
                    </Link>
                  </div>
                </div>
              </IceFormBinderWrapper>
            </Fragment>
          )
        }
        {
          editorHost && (
            <Fragment>
              <Form style={{ width: '100%' }} inline labelAlign="inset" labelCol={{ fixedSpan: 4 }} wrapperCol={{ span: 20 }}>
                <div style={styles.formItem1}>
                  <FormItem label="" required requiredMessage="请填写服务器名称" style={{ width: '100%' }}>
                    <Input name="hostTitle" placeholder="请填写服务器名称" defaultValue="" />
                  </FormItem>
                </div>
                <div style={styles.formItem1}>
                  <FormItem label="" required requiredMessage="请填写服务器地址" style={{ width: '100%' }}>
                    <Input name="hostLink" defaultValue="" placeholder="请填写服务器地址" />
                  </FormItem>
                </div>
                <FormItem label="" style={{ width: '100%', textAlign: 'right', display: 'flex' }}>
                  <Form.Submit type="primary" size="small" validate onClick={this.addHost}>保存</Form.Submit>
                  <span onClick={this.hideEditorHost} style={{ color: '#447eff', textDecoration: 'underline', marginLeft: '10px', position: 'relative' }}>
                    返回
                  </span>
                </FormItem>
              </Form>
              <Table dataSource={hostList}>
                <Table.Column title="名称" dataIndex="hostTitle" />
                <Table.Column title="链接" dataIndex="hostLink" />
                <Table.Column cell={this.renderDel} />
              </Table>
            </Fragment>
          )
        }
      </div>
    );
  }
}

const styles = {
  container: {
    width: '400px',
    padding: '40px',
    background: '#fff',
    borderRadius: '6px',
  },
  title: {
    margin: '0 0 40px',
    color: 'rgba(0, 0, 0, 0.8)',
    fontSize: '28px',
    fontWeight: '500',
    textAlign: 'center',
  },
  formItem: {
    position: 'relative',
    marginBottom: '20px',
  },
  formItem1: {
    position: 'relative',
  },
  inputIcon: {
    position: 'absolute',
    left: '10px',
    top: '6px',
    color: '#666',
  },
  setIcon: {
    position: 'absolute',
    right: '5px',
    top: '8px',
    color: '#666',
  },
  selector: {
    width: '80%',
  },
  inputCol: {
    width: '100%',
    paddingLeft: '20px',
  },
  submitBtn: {
    width: '100%',
  },
  tips: {
    position: 'relative',
    marginTop: '20px',
    display: 'block',
    textAlign: 'center',
  },
};

export default UserLogin;
